﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BaseDll;
using CommonTools;
using MotionIoLib;
using Sunny.UI;
using UserCtrl;
using System.Reflection;
namespace StationDemo
{
    public partial class StationFormRobot : UIPage
    {
        public BaseScaraRobot scaraRobot = null;
        private readonly Stationbase _stationBase;
        private object obj_Param = null;
        private object obj_Point = null;
        private Dictionary<string, UserIoInput> _stationInputDic;
        private Dictionary<string, UserIOOutPut> _stationOutputDic;
        private UIPage Page_Manual = null;
        public StationFormRobot(BaseScaraRobot robot,Stationbase stationbase,object obj_Param, object obj_Point,object obj_Config, UIPage ui_Manual = null)
        {
            InitializeComponent();
            scaraRobot = robot;
            _stationBase = stationbase;
            this.obj_Point = obj_Point;
            this.obj_Param = obj_Param;
            propertyGrid_Config.SelectedObject = obj_Config;
            Page_Manual = ui_Manual;
            //LanguageSet.Instance.RegForm(this);
        }
        private void button_Save_Click(object sender, EventArgs e)
        {
            string strPointNameErr = "";
            try
            {
                if (!this.ShowAskDialog("是否保存所有点位！", UIStyle.Blue)) return;
                Dictionary<string, Coordinate> staPoint_New = new Dictionary<string, Coordinate>();
                Dictionary<string, Coordinate> staPoint_Old = _stationBase.GetFields<Coordinate>(obj_Point);
                for (int i = 0; i < dataGridView_PointInfo.Rows.Count; i++)
                {
                    if (dataGridView_PointInfo.Rows[i].Cells[0].Value != null && dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString() != "")
                    {
                        int index = 1;
                        Coordinate point = new Coordinate();
                        string strName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString());
                        point.X = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.Y = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.Z = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.U = Convert.ToDouble(dataGridView_PointInfo.Rows[i].Cells[index++].Value);
                        point.Direction= (HandDirection)Enum.Parse(typeof(HandDirection), dataGridView_PointInfo.Rows[i].Cells[index++].Value.ToString());
                        string str_PointInfo = $"站位名称：{this.Name}，点位名称：{strName},X={point.X}，Y={point.Y}，Z={point.Z}，U={point.U}";
                        staPoint_New.Add(strName, point);
                    }
                }
                if (obj_Point == null) return;
                FieldInfo[] list_Field = obj_Point.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                if (list_Field.Length <= 0) return;
                foreach (var item in list_Field)
                {
                    string str_Name = item.Name;
                    for (int i = 0; i < staPoint_New.Count; i++)
                    {
                        if (item.Name == staPoint_New.Keys.ToList()[i])
                        {
                            Coordinate coordOld = (Coordinate)item.GetValue(obj_Point);
                            Coordinate coordNew = staPoint_New.Values.ToList()[i];
                            if (coordOld.X != coordNew.X || coordOld.Y != coordNew.Y  ||
                                coordOld.U != coordNew.U || coordOld.Z != coordNew.Z|| coordNew.Direction != coordNew.Direction)
                            {
                                string strOldValue = $"X={coordOld.X},Y={coordOld.Y},Z={coordOld.Z},U{coordOld.U},Hand={coordOld.Direction}";
                                string strNewValue = $"X={coordNew.X},Y={coordNew.Y},Z={coordNew.Z},U{coordNew.U},Hand={coordNew.Direction}";
                                DeviceDataCollect.GetInstance().Function_PointChangeLog(_stationBase.Name, str_Name, strOldValue, strNewValue);
                            }

                            item.SetValue(obj_Point, staPoint_New.Values.ToList()[i]);
                        }
                    }
                }
                ConfigToolMgr.GetInstance().SaveScaraRobotPoint(this.Name, staPoint_New);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                this.ShowErrorDialog($"点位数据：{strPointNameErr} 错误 ");
            }
        }
        private void button_RecordPoint_Click(object sender, EventArgs e)
        {

            string strPointErrName = "";
            try
            {
                if (!UIMessageDialog.ShowMessageDialog("是否记录此点到点位表格！", "Info", true, UIStyle.Blue, true)) return;
                int nAxisNot = _stationBase.AxisX;
                if (dataGridView_PointInfo.CurrentCell != null)
                {
                    int indexRow = dataGridView_PointInfo.CurrentCell.RowIndex;
                    int indexCol = dataGridView_PointInfo.CurrentCell.ColumnIndex;
                    string strPointName = dataGridView_PointInfo.Rows[indexRow].Cells[0].Value.ToString();
                    strPointErrName = strPointName;
                    string[] strPointNameArr = new string[dataGridView_PointInfo.Rows.Count];
                    for (int i = 0; i < dataGridView_PointInfo.Rows.Count; i++)
                    {
                        if (dataGridView_PointInfo.Rows[i].Cells[0].Value != null && dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString() != "")
                            strPointNameArr[i] = dataGridView_PointInfo.Rows[i].Cells[0].Value.ToString();
                    }
                    Coordinate tempPoint = new Coordinate();
                    if (dataGridView_PointInfo.CurrentCell.ColumnIndex == 0)
                    {
                        tempPoint = scaraRobot.GetCurrentCoordinate();

                    }
                    else
                    {
                        tempPoint.X = dataGridView_PointInfo.Rows[indexRow].Cells[1].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[1].Value.ToString());
                        tempPoint.Y = dataGridView_PointInfo.Rows[indexRow].Cells[2].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[2].Value.ToString());
                        tempPoint.Z = dataGridView_PointInfo.Rows[indexRow].Cells[3].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[3].Value.ToString());
                        tempPoint.U = dataGridView_PointInfo.Rows[indexRow].Cells[4].Value == null ? 0 : StringEx.ToDouble(dataGridView_PointInfo.Rows[indexRow].Cells[4].Value.ToString());
                        tempPoint.Direction = dataGridView_PointInfo.Rows[indexRow].Cells[5].Value == null ? 0 : (HandDirection)Enum.Parse(typeof(HandDirection), dataGridView_PointInfo.Rows[indexRow].Cells[5].Value.ToString());
                        switch (dataGridView_PointInfo.CurrentCell.ColumnIndex)
                        {
                            case 1:
                                tempPoint.X = scaraRobot.GetCurrentCoordinate().X;
                                break;
                            case 2:
                                tempPoint.Y = scaraRobot.GetCurrentCoordinate().Y;
                                break;
                            case 3:
                                tempPoint.Z = scaraRobot.GetCurrentCoordinate().Z;
                                break;
                            case 4:
                                tempPoint.U = scaraRobot.GetCurrentCoordinate().U;
                                break;
                            case 5:
                                tempPoint.Direction = scaraRobot.GetCurrentCoordinate().Direction;
                                break;
                        }
                    }
                    dataGridView_PointInfo.Rows[indexRow].Cells[1].Value = Math.Round(tempPoint.X, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[2].Value = Math.Round(tempPoint.Y, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[3].Value = Math.Round(tempPoint.Z, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[4].Value = Math.Round(tempPoint.U, 3);
                    dataGridView_PointInfo.Rows[indexRow].Cells[5].Value = tempPoint.Direction.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                this.ShowErrorDialog($"点位数据：{strPointErrName} 错误 ");
            }
        }

        private void EnableBtns(bool bEnable)
        {
            button_Zpositive.Enabled = bEnable;
            button_Znegtive.Enabled = bEnable;
            button_Ypositive.Enabled = bEnable;
            button_Ynegtive.Enabled = bEnable;
            button_Upositive.Enabled = bEnable;
            button_Unegtive.Enabled = bEnable;
            button_Xnegtive.Enabled = bEnable;
            button_Xpositive.Enabled = bEnable;
            btnSingleAxisMove.Enabled = bEnable;
        }

        private void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            scaraRobot.ResetRobot();
        }

        private void button_Zpositive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;
            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            button_Zpositive.Text = "Z+Moving";
            button_Zpositive.BackColor = Color.LightBlue;
            button_Zpositive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                coordinate.Z = coordinate.Z + strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                // while (!ts.IsCompleted)
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Zpositive.Invoke(
                      new Action(() =>
                      {
                          button_Zpositive.Enabled = true;
                          button_Zpositive.Text = "Z+";
                          button_Zpositive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }

        private void button_Xnegtive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;
            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            button_Xnegtive.Text = "X-Moving";
            button_Xnegtive.BackColor = Color.LightBlue;
            button_Xnegtive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                // SelMoveType("抓放料机械手", strSelDistance, 0, false, 10);
                coordinate.X = coordinate.X - strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                // scaraRobot.Jump(coordinate, handDirection, -1);
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Xnegtive.Invoke(
                      new Action(() =>
                      {
                          button_Xnegtive.Enabled = true;
                          button_Xnegtive.Text = "X-";
                          button_Xnegtive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }

        private void button_Xpositive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;
            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            button_Xpositive.Text = "X+Moving";
            button_Xpositive.BackColor = Color.LightBlue;
            button_Xpositive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                // SelMoveType("抓放料机械手", strSelDistance, 0, true, 10);
                coordinate.X = coordinate.X + strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                //  scaraRobot.Jump(coordinate, handDirection, -1);
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Xpositive.Invoke(
                      new Action(() =>
                      {
                          button_Xpositive.Enabled = true;
                          button_Xpositive.Text = "X+";
                          button_Xpositive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }

        private void button_Ypositive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;
           
            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            button_Ypositive.Text = "Y+Moving";
            button_Ypositive.BackColor = Color.LightBlue;
            button_Ypositive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                coordinate.Y = coordinate.Y + strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Ypositive.Invoke(
                      new Action(() =>
                      {
                          button_Ypositive.Enabled = true;
                          button_Ypositive.Text = "Y+";
                          button_Ypositive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }

        private void button_Ynegtive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;
            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();

            button_Ynegtive.Text = "Y-Moving";
            button_Ynegtive.BackColor = Color.LightBlue;
            button_Ynegtive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                coordinate.Y = coordinate.Y - strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Ynegtive.Invoke(
                      new Action(() =>
                      {
                          button_Ynegtive.Enabled = true;
                          button_Ynegtive.Text = "Y-";
                          button_Ynegtive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }

        private void button_Upositive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;
            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            button_Upositive.Text = "U+Moving";
            button_Upositive.BackColor = Color.LightBlue;
            button_Upositive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                //SelMoveType("抓放料机械手", strSelDistance, 3, true, 10);
                coordinate.U = coordinate.U + strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                // while (!ts.IsCompleted)
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Upositive.Invoke(
                      new Action(() =>
                      {
                          button_Upositive.Enabled = true;
                          button_Upositive.Text = "U+";
                          button_Upositive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }

        private void button_Unegtive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;

            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            //  SelMoveType("抓放料机械手", strSelDistance, 3, false, 10);
            button_Unegtive.Text = "U-Moving";
            button_Unegtive.BackColor = Color.LightBlue;
            button_Unegtive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                coordinate.U = coordinate.U - strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                // while (!ts.IsCompleted)
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Unegtive.Invoke(
                      new Action(() =>
                      {
                          button_Unegtive.Enabled = true;
                          button_Unegtive.Text = "U-";
                          button_Unegtive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }
        private void button_ServoOnX_Click(object sender, EventArgs e)
        {
            if (button_ServoOn.Active)
            {
                scaraRobot.ServoOn(false);
            }
            else
            {
                scaraRobot.ServoOn(true);
            }
        }
        public void ChangedUserRight(User CurrentUser)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => ChangedUserRight(CurrentUser)));
            else
            {

                switch ((int)CurrentUser._userRight)
                {
                    case (int)UserRight.Operator:
                        button_RecordPoint.Enabled = false;
                        button_Save.Enabled = false;
                        btnSingleAxisMove.Enabled = false;
                        dataGridView_PointInfo.ReadOnly = true;

                        break;
                    case (int)UserRight.Debug:
                        button_RecordPoint.Enabled = false;
                        button_Save.Enabled = false;
                        btnSingleAxisMove.Enabled = true;
                        dataGridView_PointInfo.ReadOnly = false;
                        break;
                    case (int)UserRight.Software:
                        button_RecordPoint.Enabled = true;
                        button_Save.Enabled = true;
                        btnSingleAxisMove.Enabled = true;
                        dataGridView_PointInfo.ReadOnly = false;
                        break;
                    case (int)UserRight.Admin:
                        button_RecordPoint.Enabled = true;
                        button_Save.Enabled = true;
                        btnSingleAxisMove.Enabled = true;
                        dataGridView_PointInfo.ReadOnly = false;
                        break;
                }
                bool bEnable = true;
                if ((int)CurrentUser._userRight >= (int)UserRight.Debug)
                {
                    bEnable = true;
                    button_ServoOn.Enabled = bEnable;


                    button_Xpositive.Enabled = bEnable;
                    button_Ypositive.Enabled = bEnable;
                    button_Zpositive.Enabled = bEnable;
                    button_Upositive.Enabled = bEnable;

                    button_Xnegtive.Enabled = bEnable;
                    button_Ynegtive.Enabled = bEnable;
                    button_Znegtive.Enabled = bEnable;
                    button_Unegtive.Enabled = bEnable;
                    foreach (var temp in this.Controls)
                    {
                        ((Control)temp).Enabled = bEnable;
                    }
                }
                else
                {
                    button_Xpositive.Enabled = bEnable;
                    button_Ypositive.Enabled = bEnable;
                    button_Zpositive.Enabled = bEnable;
                    button_Upositive.Enabled = bEnable;

                    button_Xnegtive.Enabled = bEnable;
                    button_Ynegtive.Enabled = bEnable;
                    button_Znegtive.Enabled = bEnable;
                    button_Unegtive.Enabled = bEnable;
                    foreach (var temp in this.Controls)
                    {
                        ((Control)temp).Enabled = bEnable;
                    }

                }
                UpdatadataGridView_ParamInfo(cbb_ParamType.Text, CurrentUser._userRight);
                GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
            }

        }
        void UpdatadataGridView_ParamInfo(string strType, UserRight userRight)
        {
            dataGridView_Param.Rows.Clear();
            Dictionary<string, ParamSet> dic_Param = _stationBase.GetFields<ParamSet>(obj_Param);
            cbb_ParamType.Items.Clear();
            dg_cbb_ParamType.Items.Clear();
            cbb_ParamType.Items.Add("all");
            foreach (var item in dic_Param)
            {
                if (!cbb_ParamType.Items.Contains(item.Value._ParamClass))
                    cbb_ParamType.Items.Add(item.Value._ParamClass);
                if (!dg_cbb_ParamType.Items.Contains(item.Value._ParamClass))
                    dg_cbb_ParamType.Items.Add(item.Value._ParamClass);
                if (item.Value._ParamRight <= userRight)
                {
                    if (item.Value._ParamClass == strType || strType == "all")
                    {
                        int index = dataGridView_Param.Rows.Add(item.Key, item.Value._enuValType.ToString().Trim(),
                          item.Value._strParamVal, item.Value._strParamValMax, item.Value._strParamValMin,
                          item.Value._ParamRight.ToString(), item.Value._ParamClass.ToString(), item.Value.b_IsStartCheck);
                        if ((int)(UserRight)Enum.Parse(typeof(UserRight), dataGridView_Param.Rows[index].Cells[5].Value.ToString()) <= (int)sys.g_User._userRight)
                        {
                            //dataGridView_Param.Rows[index].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[0].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[1].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[2].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[3].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[4].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[5].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[6].ReadOnly = false;
                            dataGridView_Param.Rows[index].Cells[7].ReadOnly = false;
                            dataGridView_Param.Rows[index].Visible = true;
                        }
                        else
                        {
                            dataGridView_Param.Rows[index].Cells[0].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[1].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[2].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[3].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[4].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[5].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[6].ReadOnly = true;
                            dataGridView_Param.Rows[index].Cells[7].ReadOnly = true;
                            dataGridView_Param.Rows[index].Visible = true;
                        }
                    }
                }
            }
            cbb_ParamType.Text = strType;
            Language.LanguageHelp.GetInstance().Funtion_TransLate(this.Name);
        }



        private void button_Znegtive_Click(object sender, EventArgs e)
        {
            if (comboBox_SelMotionType.SelectedItem == null)
                return;


            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            button_Znegtive.Text = "Z-Moving";
            button_Znegtive.BackColor = Color.LightBlue;
            button_Znegtive.Enabled = false;
            EnableBtns(false);
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                // SelMoveType("抓放料机械手", strSelDistance, 2, false, 10);
                coordinate.Z = coordinate.Z - strSelDistance.ToDouble();
                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                scaraRobot.Go(coordinate);

                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                //while (!ts.IsCompleted)
                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                       UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }

                }
                button_Znegtive.Invoke(
                      new Action(() =>
                      {
                          button_Znegtive.Enabled = true;
                          button_Znegtive.Text = "Z-";
                          button_Znegtive.BackColor = Color.LightGreen;
                          EnableBtns(true);
                      })
                     );

            });
        }

        private int GetMaxOutputLength(Dictionary<string, string> pageMaxLengthDic, KeyValuePair<string, UIPage> uiPage)
        {
            string maxLengthIo = pageMaxLengthDic[uiPage.Key];
            UserIOOutPut tmpOutPut = new UserIOOutPut { IOName = maxLengthIo };
            return tmpOutPut.Width + 50;
        }

        private int GetMaxInputLength(List<string> listString)
        {
            int n_Length = 0;
            for (int i = 0; i < listString.Count; i++)
            {
                UserIOOutPut tmpOutPut = new UserIOOutPut { IOName = listString[i] };
                n_Length = n_Length > tmpOutPut.Width ? n_Length : tmpOutPut.Width;
            }
            return n_Length + 50;
        }
        private void StationFormRobot_Load(object sender, EventArgs e)
        {
            iniInput();
            iniOutput();
            for (int i = 0; i < dataGridView_PointInfo.Columns.Count; i++)
            {
                dataGridView_PointInfo.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            UpdatadataGridView_PointInfo();
            ParamSetMgr.GetInstance().m_eventLoadProductFileUpadata += UpdatadataGridView_PointInfo;//更新产品点位置信息
            UpdatadataGridView_ParamInfo("all", sys.g_User._userRight);

            RobotMotionMgr.GetInstace().m_eventChangePos += UpdataRobotPos;
            RobotMotionMgr.GetInstace().m_eventConnectState += UpdataConnectState;
            RobotMotionMgr.GetInstace().m_eventChangeHandDirection += UpdataHandDirectionState;
            RobotMotionMgr.GetInstace().m_eventServoState += UpdataServoOn;
            RobotMotionMgr.GetInstace().m_eventIoInputChanage += ChangedIoInState;
            RobotMotionMgr.GetInstace().m_eventIoOutChanage += ChangedIoOutState;
            UpdataRobotPos(scaraRobot.strName, scaraRobot.GetCurrentCoordinate());
            UpdataConnectState(scaraRobot.strName, scaraRobot.IsConnect());
            UpdataHandDirectionState(scaraRobot.strName, scaraRobot.GetCurrentHandDirection());
            UpdataServoOn(scaraRobot.strName, scaraRobot.IsServoOn());
            foreach (var item in scaraRobot.dic_IoIn)
            {
                ChangedIoInState(scaraRobot.strName, item.Key, scaraRobot.GetInBit(item.Value));
            }
            foreach (var item in scaraRobot.dic_IoOut)
            {
                ChangedIoOutState(scaraRobot.strName, item.Key, scaraRobot.GetOutBit(item.Value));
            }
            comboBox_SelMotionType.SelectedIndex = 4;

            if (Page_Manual != null)
            {
                tab_ManualTest.Controls.Add(Page_Manual);
                Page_Manual.Show();
            }

            sys.g_eventRightChanged += ChangedUserRight;
            GlobalVariable.g_eventStationStateChanged += GlobalVariable_g_eventStationStateChanged;
            GlobalVariable.g_eventControlModeChanged += GlobalVariable_g_eventControlModeChanged;
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }
        private void GlobalVariable_g_eventControlModeChanged(ControlMode currRunMode)
        {
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }
        private void GlobalVariable_g_eventStationStateChanged(StationState currState)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => GlobalVariable_g_eventStationStateChanged(currState)));
            else
            {
                if ((int)sys.g_User._userRight >= (int)UserRight.Debug && (GlobalVariable.g_StationState == StationState.StationStateEmg || GlobalVariable.g_StationState == StationState.StationStateStop))
                {
                    if ((int)sys.g_User._userRight >= (int)UserRight.Debug &&
                    GlobalVariable.g_ControlMode != ControlMode.Auto)
                    {
                        tabInput.Enabled = true;
                        tabOutput.Enabled = true;
                        PanControl.Enabled = true;
                        propertyGrid_Config.Enabled = true;
                        if (Page_Manual != null)
                            Page_Manual.Enabled = true;
                    }
                    dataGridView_Param.Enabled = true;
                 
                }
                else
                {
                    tabInput.Enabled = false;
                    tabOutput.Enabled = false;
                    PanControl.Enabled = false;
                    Page_Manual.Enabled = false;
                    propertyGrid_Config.Enabled = false;
                    dataGridView_Param.Enabled = false;
                }
            }

        }

        private void UpdataConnectState(string strRobotName, bool b_State)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => UpdataConnectState(strRobotName, b_State)));
            else
            {
                if(scaraRobot.strName!=strRobotName)
                {
                    return;
                }
                if (b_State)
                {
                    lbl_ConnectState.Text = "已连接";
                    lbl_ConnectState.BackColor = Color.Green;
                }
                else
                {
                    lbl_ConnectState.Text = "未连接";
                    lbl_ConnectState.BackColor = Color.Red;

                }
            }
        }
        private void UpdataHandDirectionState(string strRobotName, HandDirection handDirection)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => UpdataHandDirectionState(strRobotName, handDirection)));
            else
            {
                if (scaraRobot.strName != strRobotName)
                {
                    return;
                }
                labelHandSystem.Text = handDirection.ToString();
            }
        }

        private void UpdataServoOn(string strRobotName, bool b_State)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => UpdataServoOn(strRobotName, b_State)));
            else
            {
                if (scaraRobot.strName != strRobotName)
                {
                    return;
                }
                button_ServoOn.Active = b_State;
            }
        }

        private void UpdataRobotPos(string strRobotName, Coordinate coordinate)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => { UpdataRobotPos(strRobotName, coordinate); }));
            }
            else
            {
                if (scaraRobot.strName != strRobotName)
                {
                    return;
                }
                label_PosX.Text = coordinate.X.ToString("F3");
                label_PosY.Text = coordinate.Y.ToString("F3");
                label_PosZ.Text = coordinate.Z.ToString("F3");
                label_PosU.Text = coordinate.U.ToString("F3");
            }

        }

        private void ChangedIoInState(string strRobotName, string IoName, bool bStateCurrent)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedIoInState(strRobotName,IoName, bStateCurrent)));
            }
            else
            {
                if(scaraRobot.strName==strRobotName)
                {
                    if (_stationInputDic.ContainsKey(IoName))
                    {
                        _stationInputDic[IoName].State = bStateCurrent;
                    }

                }

            }
        }
        private void ChangedIoOutState(string strRobotName, string IoName, bool bStateCurrent)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedIoOutState(strRobotName,IoName, bStateCurrent)));
            }
            else
            {
                if (scaraRobot.strName == strRobotName)
                {
                    if (_stationOutputDic.ContainsKey(IoName))
                    {
                        _stationOutputDic[IoName].State = bStateCurrent;
                    }

                }
            }

        }
        void iniInput()
        {
            Dictionary<string, int> dicInput = scaraRobot.dic_IoIn;//所有输出点字典
            #region 获取每页最长名称

            List<string> list_IoName = new List<string>(); ;//每页最长字符<页名称，IO名称>
            foreach (var key in dicInput.Keys)
            {
                list_IoName.Add(key);
            }

            #endregion

            #region 获取页名查找页面的字典
            tabInput.TabPages.Clear();
            UIPage uiPage = new UIPage { Text = "输入", AutoScroll = true };
            tabInput.AddPage(uiPage);
            #endregion

            #region 将IO添加到对应的分页容器

            int panWidth = tabPage4.Width;
            _stationInputDic = new Dictionary<string, UserIoInput>();
            int top = 0;
            int left = 0;
            int maxLength = GetMaxInputLength(list_IoName);//获取最长IO长度作为列宽

            foreach (var item in dicInput)
            {
                UserIoInput input = new UserIoInput();
                uiPage.Controls.Add(input);
                _stationInputDic.Add(item.Key, input);
                input.IOName = item.Key;
                input.Height = 40;

                if (left + maxLength > panWidth)
                {
                    left = 0;
                    top += input.Height;
                }
                input.Left = left;
                input.Top = top;
                left += maxLength;
            }
            #endregion

        }


         void iniOutput()
        {
            Dictionary<string, int> dicOutput = scaraRobot.dic_IoOut;//所有输出点字典
            #region 获取每页最长名称

            List<string> list_IoName = new List<string>(); ;//每页最长字符<页名称，IO名称>
            foreach (var key in dicOutput.Keys)
            {
                list_IoName.Add(key);
            }

            #endregion

            #region 获取页名查找页面的字典
            tabOutput.TabPages.Clear();
            UIPage uiPage = new UIPage { Text = "输出", AutoScroll = true };
            tabOutput.AddPage(uiPage);
            #endregion

            #region 将IO添加到对应的分页容器

            int panWidth = tabPage4.Width;
            _stationOutputDic = new Dictionary<string, UserIOOutPut>();
            int top = 0;
            int left = 0;
            int maxLength = GetMaxInputLength(list_IoName);//获取最长IO长度作为列宽

            foreach (var item in dicOutput)
            {
                UserIOOutPut Output = new UserIOOutPut();
                uiPage.Controls.Add(Output);
                _stationOutputDic.Add(item.Key, Output);
                Output.StateChanged += Output_Click;
                Output.IOName = item.Key;
                Output.Height = 40;

                if (left + maxLength > panWidth)
                {
                    left = 0;
                    top += Output.Height;
                }
                Output.Left = left;
                Output.Top = top;
                left += maxLength;
            }
            #endregion
        }
        private void Output_Click(string ioName, bool state)
        {
            string strIOName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name, ioName);
            bool bState = RobotMotionMgr.GetInstace().GetOutBit(scaraRobot.strName, strIOName);
            RobotMotionMgr.GetInstace().SetOutput(scaraRobot.strName, strIOName, !bState);
        }
        void UpdatadataGridView_PointInfo()
        {
            dataGridView_PointInfo.Rows.Clear();
            Dictionary<string, Coordinate> tempdic = _stationBase.GetFields<Coordinate>(obj_Point);
            foreach (var temp in tempdic)
            {
                dataGridView_PointInfo.Rows.Add(temp.Key, temp.Value.X.ToString(),temp.Value.Y.ToString(), 
                                                temp.Value.Z.ToString(), temp.Value.U.ToString(), temp.Value.Direction.ToString());

            }
            Language.LanguageHelp.GetInstance().Funtion_TransLate(this.Name);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            scaraRobot.Stop();
        }

        #region 机器人点动
        private void JogStart(object sender, MouseEventArgs e)
        {
            return;
            
        }
        private void JogEnd(object sender, MouseEventArgs e)
        {
            return;
        }
        #endregion

        private void btnSingleAxisMove_Click(object sender, EventArgs e)
        {
            if (!UIMessageDialog.ShowMessageDialog("是否进行单轴运动，请注意安全！", "Info", true, UIStyle.Blue, true)) return;
            if (dataGridView_PointInfo.CurrentCell == null)
                return;
            int indexRow = dataGridView_PointInfo.CurrentCell.RowIndex;
            int indexCol = dataGridView_PointInfo.CurrentCell.ColumnIndex;
            if (indexCol == 0)
                return;
            double pos = Convert.ToDouble(dataGridView_PointInfo.CurrentCell.Value.ToString());
            if (comboBox_SelMotionType.SelectedItem == null)
                return;
            EnableBtns(false);

            string strSelDistance = comboBox_SelMotionType.SelectedItem.ToString();
            Coordinate coordinate = scaraRobot.GetCurrentCoordinate().Copy();
            Task ts = new Task(delegate ()
            {
                switch (indexCol)
                {
                    case 1:
                        coordinate.X = pos;
                        break;
                    case 2:
                        coordinate.Y = pos;
                        break;
                    case 3:
                        coordinate.Z = pos;
                        break;
                    case 4:
                        coordinate.U = pos;
                        break;
                    default:
                        return;
                }

                HandDirection handDirection = scaraRobot.GetCurrentHandDirection();
                scaraRobot.Go(coordinate);
                Thread.Sleep(100);
            });
            ts.Start();
            ts.ContinueWith((ts1) =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();

                while (!scaraRobot.InPos(coordinate))
                {
                    if (stopwatch.ElapsedMilliseconds > 90 * 1000)
                    {
                        UIMessageBox.ShowError("机械人90秒超时" + "运动失败");
                        break;
                    }
                }
                btnSingleAxisMove.Invoke(new Action(() =>
                                          {
                                              EnableBtns(true);
                                          })
                                         );
            });


        }

        private void cbb_ParamType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btn_SaveParam_Click(object sender, EventArgs e)
        {

        }

        private void cbb_ParamType_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            UpdatadataGridView_ParamInfo(cbb_ParamType.Text, sys.g_User._userRight);
        }
        List<string> ItemName = new List<string>();
        private bool Check()
        {
            try
            {
                ItemName.Clear();
                for (int i = 0; i < dataGridView_Param.Rows.Count ; i++)
                {
                    string name = dataGridView_Param.Rows[i].Cells[0].Value.ToString().Trim();
                    string sort = dataGridView_Param.Rows[i].Cells[6].Value.ToString().Trim();
                    string type = dataGridView_Param.Rows[i].Cells[1].Value.ToString().Trim();
                    string value = dataGridView_Param.Rows[i].Cells[2].Value.ToString().Trim();
                    string Max = dataGridView_Param.Rows[i].Cells[3].Value.ToString().Trim();
                    string Min = dataGridView_Param.Rows[i].Cells[4].Value.ToString().Trim();
                    dynamic v; dynamic vMax; dynamic vMin;

                    if (type == "boolUnit")
                    {
                        if (value.ToLower() != "true" && value.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入false或者true");
                            return false;
                        }
                        if (Max.ToLower() != "true" && Max.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入false或者true");
                            return false;
                        }
                        if (Min.ToLower() != "true" && Min.ToLower() != "false")
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入false或者true");
                            return false;
                        }
                    }
                    else if (type == "intUnit")
                    {

                        if (value.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，有小数点");
                            return false;
                        }
                        if (Max.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，有小数点");
                            return false;
                        }
                        if (Min.Contains("."))
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，有小数点");
                            return false;
                        }
                        try
                        {
                            v = Convert.ToInt32(value);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMax = Convert.ToInt32(Max);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMin = Convert.ToInt32(Min);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入int类型数据");
                            return false;
                        }
                        if (v > vMax || v < vMin)
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，不在规格内");
                            return false;
                        }
                    }
                    else if (type == "doubleUnit")
                    {
                        try
                        {
                            v = Convert.ToDouble(value);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMax = Convert.ToDouble(Max);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，Max设置失败，请输入int类型数据");
                            return false;
                        }
                        try
                        {
                            vMin = Convert.ToDouble(Min);
                        }
                        catch
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，min设置失败，请输入int类型数据");
                            return false;
                        }
                        if (v > vMax || v < vMin)
                        {
                            UIMessageBox.ShowError($"类别:{sort}名称:{name}，value设置失败，不在规格内");
                            return false;
                        }

                    }
                    else if (type == "stringUnit")
                    {

                    }
                    if (ItemName.Contains(name))
                    {
                        UIMessageBox.ShowError($"第{i}行存在重名参数{name},请检查");
                        return false;
                    }
                    ItemName.Add(name);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return false;
            }

        }

        private void btn_SaveParam_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (!this.ShowAskDialog("是否保存该工站参数！", UIStyle.Blue)) return;
                if (!Check())
                    return;
                Dictionary<string, ParamSet> staParam_New = _stationBase.GetFields<ParamSet>(obj_Param);
                for (int i = 0; i < dataGridView_Param.Rows.Count; i++)
                {
                    if (dataGridView_Param.Rows[i].Cells[0].Value != null && dataGridView_Param.Rows[i].Cells[0].Value.ToString() != "")
                    {
                        int nIndexOfMax = 3;
                        int nIndexOfMin = 4;
                        int nIndexOfVal = 2;
                        int nIndexOfClass = 6;
                        int nIndexOfRight = 5;
                        int nIndexOfName = 0;
                        int nIndexOfUnit = 1;
                        int nIndexOfbIsStartCheck = 7;
                        string strParamName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfName].Value.ToString());
                        string strValType = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name, dataGridView_Param.Rows[i].Cells[nIndexOfUnit].Value.ToString());
                        string strParamVal = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfVal].Value.ToString());
                        string strParamValMax = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name, dataGridView_Param.Rows[i].Cells[nIndexOfMax].Value.ToString());
                        string strParamValMin = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfMin].Value.ToString());
                        string strParamRight = dataGridView_Param.Rows[i].Cells[nIndexOfRight].Value.ToString();
                        string strParamClass = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name,  dataGridView_Param.Rows[i].Cells[nIndexOfClass].Value.ToString());
                        ParamSet paramSet = new ParamSet()
                        {
                            _strParamUnit = strParamName,
                            _enuValType = dataGridView_Param.Rows[i].Cells[nIndexOfUnit].Value == null ? ParamSetUnit.doubleUnit : (ParamSetUnit)Enum.Parse(typeof(ParamSetUnit), strValType),
                            _strParamVal = dataGridView_Param.Rows[i].Cells[nIndexOfVal].Value == null ? "0" : strParamVal,
                            _strParamValMax = dataGridView_Param.Rows[i].Cells[nIndexOfMax].Value == null ? "0" : strParamValMax,
                            _strParamValMin = dataGridView_Param.Rows[i].Cells[nIndexOfMin].Value == null ? "0" : strParamValMin,
                            _ParamRight = dataGridView_Param.Rows[i].Cells[nIndexOfRight].Value == null ? UserRight.Operator : (UserRight)Enum.Parse(typeof(UserRight), strParamRight),
                            _ParamClass = dataGridView_Param.Rows[i].Cells[nIndexOfClass].Value == null ? "综合" : strParamClass,
                            b_IsStartCheck = Convert.ToBoolean(dataGridView_Param.Rows[i].Cells[nIndexOfbIsStartCheck].Value)
                        };
                        if (paramSet._enuValType == ParamSetUnit.boolUnit)
                        {
                            paramSet._strParamVal = Convert.ToBoolean(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToBoolean(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToBoolean(paramSet._strParamValMin);
                        }
                        else if (paramSet._enuValType == ParamSetUnit.doubleUnit)
                        {
                            paramSet._strParamVal = Convert.ToDouble(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToDouble(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToDouble(paramSet._strParamValMin);
                        }
                        else if (paramSet._enuValType == ParamSetUnit.intUnit)
                        {
                            paramSet._strParamVal = Convert.ToInt32(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToInt32(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToInt32(paramSet._strParamValMin);
                        }
                        else if (paramSet._enuValType == ParamSetUnit.stringUnit)
                        {
                            paramSet._strParamVal = Convert.ToString(paramSet._strParamVal);
                            paramSet._strParamValMax = Convert.ToString(paramSet._strParamValMax);
                            paramSet._strParamValMin = Convert.ToString(paramSet._strParamValMin);
                        }
                        string str_PointInfo = $"站位名称：{this.Name}，参数名称：{strParamName}，参数值：{strParamVal}";
                        staParam_New[strParamName] = paramSet;
                    }
                }
                if (obj_Param == null) return;
                FieldInfo[] list_Field = obj_Param.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                if (list_Field.Length <= 0) return;
                foreach (var item in list_Field)
                {
                    string str_Name = item.Name;
                    for (int i = 0; i < staParam_New.Count; i++)
                    {
                        if (item.Name == staParam_New.Keys.ToList()[i])
                        {
                            ParamSet paramOld = (ParamSet)item.GetValue(obj_Param);
                            ParamSet paramNew = staParam_New.Values.ToList()[i];
                            if (paramOld._strParamVal != paramNew._strParamVal)
                                BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog(this.Name, str_Name, Convert.ToString(paramOld._strParamVal), Convert.ToString(paramNew._strParamVal), "值");
                            if (paramOld._strParamValMax != paramNew._strParamValMax)
                                BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog(this.Name, str_Name, Convert.ToString(paramOld._strParamValMax), Convert.ToString(paramNew._strParamValMax), "最大值");
                            if (paramOld._strParamValMin != paramNew._strParamValMin)
                                BaseDll.DeviceDataCollect.GetInstance().Function_ParamChangeLog(this.Name, str_Name, Convert.ToString(paramOld._strParamValMin), Convert.ToString(paramNew._strParamValMin), "最小值");

                            item.SetValue(obj_Param, staParam_New.Values.ToList()[i]);
                        }
                    }
                }

                ConfigToolMgr.GetInstance().SaveStationParam(this.Name, staParam_New);
                for (int i = 0; i < dataGridView_Param.RowCount; i++)
                {

                    if (dataGridView_Param.Rows[i].Cells[2].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[2].Style.BackColor = Color.White;
                    if (dataGridView_Param.Rows[i].Cells[3].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[3].Style.BackColor = Color.White;
                    if (dataGridView_Param.Rows[i].Cells[4].Style.BackColor == Color.Yellow)
                        dataGridView_Param.Rows[i].Cells[4].Style.BackColor = Color.White;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
            }

        }

        private void button_ServoOn_ValueChanged(object sender, bool value)
        {

        }

        private void dataGridView_Param_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int RowIndex = dataGridView_Param.CurrentCell.RowIndex;
                int ColumnIndex = dataGridView_Param.CurrentCell.ColumnIndex;
                if (ColumnIndex == 2 || ColumnIndex == 3 || ColumnIndex == 4)
                {
                    string valType = ColumnIndex == 2 ? "参数值" : ColumnIndex == 3 ? " 最大值" : "最小值";
                    string oldData = dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString();
                    string paramname = dataGridView_Param[0, RowIndex].Value.ToString();
                    if (ColumnIndex == 2 && (dataGridView_Param[1, RowIndex].Value != null &&
                         dataGridView_Param[3, RowIndex].Value != null &&
                         dataGridView_Param[4, RowIndex].Value != null
                         ))
                    {

                        InputDataToDataGridView(RowIndex, ColumnIndex, dataGridView_Param[3, RowIndex].Value.ToString(), dataGridView_Param[4, RowIndex].Value.ToString());
                        string newData = dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                        UIMessageTipHelper.ShowInfoTip(dataGridView_Param.GetParentForm(), $"参数：{paramname}  {valType}被修改 原值：{oldData} --> 现值:{newData}", TipStyle.Gray, 1500);
                    }
                    if (dataGridView_Param[1, RowIndex].Value != null && (ColumnIndex == 3 || ColumnIndex == 4))
                    {
                        InputDataToDataGridView(RowIndex, ColumnIndex, "", "");
                        string newData = dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                        UIMessageTipHelper.ShowInfoTip(dataGridView_Param.GetParentForm(), $"参数：{paramname} {valType}被修改 原值：{oldData} --> 现值:{newData}", TipStyle.Gray, 1500);

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
            }

        }

        private void InputDataToDataGridView(int RowIndex, int ColumnIndex, string max, string min)
        {
            bool bRtnInput = false;
            switch (Enum.Parse(typeof(ParamSetUnit), dataGridView_Param[1, RowIndex].Value?.ToString()))
            {

                case ParamSetUnit.intUnit:
                    int nMax = max != "" ? max.ToInt() : int.MaxValue;
                    int nMin = min != "" ? min.ToInt() : int.MinValue;

                    int valueInt = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToInt();
                    bRtnInput = UIInputDialog.InputIntegerDialog(this, ref valueInt, true, "请输入数字：");
                    if (bRtnInput)
                    {

                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString().ToInt() != valueInt)
                        {
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueInt;
                        }
                    }
                    int dOldValint = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToInt();
                    if (valueInt == dOldValint) bRtnInput = true;
                    break;
                case ParamSetUnit.doubleUnit:
                    double dMax = max != "" ? max.ToDouble() : double.MaxValue;
                    double dMin = min != "" ? min.ToDouble() : double.MinValue;
                    double valueDouble = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToDouble();
                    bRtnInput = UIInputDialog.InputDoubleDialog(this, ref valueDouble, 3, true, "请输入数字：");
                    if (bRtnInput)
                    {
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString().ToDouble() != valueDouble)
                        {

                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueDouble;
                        }
                    }
                    double dOldValdouble = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToDouble();
                    if (valueDouble == dOldValdouble)
                        bRtnInput = true;
                    break;
                case ParamSetUnit.boolUnit:
                    int selectIndex = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? 0 : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString().ToUpper() == "TRUE" ? 0 : 1;
                    List<string> items = new List<string>() { "True", "False" };
                    bRtnInput = this.ShowSelectDialog(ref selectIndex, items, "是否选择".Trim(), "", UIStyle.Blue);
                    if (bRtnInput)
                    {
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString() != items[selectIndex])
                        {
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                            dataGridView_Param[ColumnIndex, RowIndex].Value = items[selectIndex];
                        }
                    }
                    if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString() == items[selectIndex])
                        bRtnInput = true;


                    break;
                case ParamSetUnit.stringUnit:
                    string valueString = dataGridView_Param[ColumnIndex, RowIndex].Value == null ? "" : dataGridView_Param[ColumnIndex, RowIndex].Value.ToString();
                    bRtnInput = UIInputDialog.InputStringDialog(this, ref valueString, false, "请输入字符：");
                    if (bRtnInput)
                    {
                        if (dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString() != valueString)
                        {
                            dataGridView_Param[ColumnIndex, RowIndex].Value = valueString;
                            ChangeDataGridViewCellBackColor(dataGridView_Param, RowIndex, ColumnIndex);
                        }
                    }
                    if (valueString == dataGridView_Param[ColumnIndex, RowIndex].Value?.ToString())
                        bRtnInput = true;

                    break;

            }
            if (!bRtnInput)
                this.ShowMessageDialog("输入值错误，可能超出上下限，请检查", "Err", true, UIStyle.Blue);
        }
        public void ChangeDataGridViewCellBackColor(DataGridView dataGridView, int RowIndex, int ColumnIndex)
        {
            DataGridViewRow dr = (dataGridView as DataGridView).Rows[RowIndex];
            dr.Cells[ColumnIndex].Style.BackColor = Color.Yellow;
            dataGridView_Param.Invalidate(dr.Cells[ColumnIndex].ContentBounds);
            dr.Cells[ColumnIndex].Selected = false;
        }

        private void dataGridView_Param_Click(object sender, EventArgs e)
        {
            try
            {
                int RowIndex = dataGridView_Param.CurrentCell.RowIndex;
                int ColumnIndex = dataGridView_Param.CurrentCell.ColumnIndex;
                if (ColumnIndex >= 0 && RowIndex >= 0)
                {
                    richTxt_参数说明.Text = $"参数名:{ dataGridView_Param[0, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"当前值:{ dataGridView_Param[2, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"允许最大值:{ dataGridView_Param[3, RowIndex].Value}" + Environment.NewLine;
                    richTxt_参数说明.Text += $"允许最小值:{ dataGridView_Param[4, RowIndex].Value}" + Environment.NewLine;
                    if (dataGridView_Param[0, RowIndex].Value == null)
                        return;
                    var de = ParamSetMgr.GetInstance().paramValue?.Find(p => p.ParamName == (dataGridView_Param[0, RowIndex].Value).ToString().Trim());
                    if (de == null)
                    {
                        richTxt_参数说明.Text += $"参数描述:还未添加描述，请在Description.xml中添加" + Environment.NewLine;
                    }
                    else
                    {
                        richTxt_参数说明.Text += $"参数描述:{ de.Description}" + Environment.NewLine;
                    }


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return;
            }

        }

        private void btn_ConfigSave_Click(object sender, EventArgs e)
        {
            try
            {
                CommonTools.ConfigToolMgr.GetInstance().SaveStationConfig(this.Name, propertyGrid_Config.SelectedObject);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Name, $"{Name}{ex.Message} {ex.StackTrace}");
                return;
            }

        }

        private void dataGridView_Param_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
    }
}
